package com.grj.parkingsystem.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.grj.parkingsystem.common.Result;
import com.grj.parkingsystem.entity.ParkingOrder;
import com.grj.parkingsystem.service.ParkingOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/order")
@Api(tags = "4. 停车订单管理")
public class ParkingOrderController {

    @Autowired
    private ParkingOrderService parkingOrderService;

    @PostMapping("/entry")
    @ApiOperation(value = "入场登记", notes = "车辆进入停车场时创建订单")
    @ApiOperationSupport(order = 1)
    public Result<?> entryParking(@ApiParam(value = "认证Token", required = true)
                                 @RequestHeader("Authorization") String token,
                                 @RequestParam Long parkingLotId,
                                 @RequestParam(required = false) Long spaceId) {
        ParkingOrder order = parkingOrderService.createEntryOrder(token, parkingLotId, spaceId);
        if (order == null) {
            return Result.error("已入场, 创建订单失败");
        }
        return Result.success(order);
    }

    @PostMapping("/exit")
    @ApiOperation(value = "出场结算", notes = "车辆离开停车场时结算订单")
    @ApiOperationSupport(order = 2)
    public Result<?> exitParking(@ApiParam(value = "认证Token", required = true)
                               @RequestHeader("Authorization") String token) {
        boolean order = parkingOrderService.exitParking(token);
        if (!order) {
            return Result.error("订单不存在或已结算");
        }
        return Result.success(order);
    }

    @GetMapping("/list")
    @ApiOperation(value = "获取订单列表", notes = "获取当前用户的停车订单列表")
    @ApiOperationSupport(order = 3)
    public Result<?> listOrders(@ApiParam(value = "认证Token", required = true)
                              @RequestHeader("Authorization") String token,
                              @RequestParam(required = false) Integer status) {
        List<ParkingOrder> orders = parkingOrderService.getUserOrders(token, status);
        return Result.success(orders);
    }

    @GetMapping("/detail/{orderId}")
    @ApiOperation(value = "获取订单详情", notes = "获取指定订单的详细信息")
    @ApiOperationSupport(order = 4)
    public Result<?> getOrderDetail(@ApiParam(value = "认证Token", required = true)
                                  @RequestHeader("Authorization") String token,
                                  @PathVariable Long orderId) {
        ParkingOrder order = parkingOrderService.getOrderDetail(token, orderId);
        return Result.success(order);
    }
}